<?php
namespace app\upapi\controller;

use think\Session;
use think\Controller;
use app\common\model\WxUser as WxUserModel;
use app\common\model\Pushmessage as PushmessageModel;
use app\common\model\AuthorWxUser;
use app\common\util\WechatThirdUtil;
use htq\HTQClient; //队列类


class Template extends Controller
{
    protected $config;
    protected $wechat_obj;
    protected $third_config;
    protected $wx_user_model;
    protected $author_wx_user;
    protected $pushmessage_model;
    protected $HTQClient;

    protected function _initialize(){
        parent::_initialize();
        $this->wx_user_model = new WxUserModel;
        $this->author_wx_user = new AuthorWxUser;
        $this->pushmessage_model = new PushmessageModel;
        // $this->config = $this->author_wx_user->where('id',1)->find(); //当前授权公众号信息(小微转头条测试)
        $this->third_config = $this->wx_user_model->find(); //第三方开发平台信息
        // $this->wechat_obj = new WechatThirdUtil($this->third_config , $this->config);
        $this->HTQClient = new HTQClient('J6E04AifABuDRfsMm2Qt4WMJHq201vmz','Hc9KVU6cGDWxoQ7PjSxwYQOLrCcg6wFj');
    }

    /*
     * 新增模板消息测试接口
     * 获取可以发送的模板消息列表
     * */
    public function getTemplateList(){
//        1 获取模板列表
        $template_list = $this->wechat_obj->getTemplateList();
        // return $this->thinkJson($template_list);
        return json($template_list);
    }

    /*
     * 模板消息的发送
     * */
    public function sendTemplateMsg($auid){
        if($this->request->isPost()){
            $data = $this->request->post();
            $template_msg = $data['data'];
            $send_openids = $template_msg['openid'];
            if(!is_array($send_openids) || empty($send_openids)){
                $this->HTQClient->deleteQueue($template_msg['queue_name']);//openids不是数组直接删除队列
                return ;
            }
            $this->config = $this->author_wx_user->where('id',$auid)->find();
            $this->wechat_obj = new WechatThirdUtil($this->third_config , $this->config);

            foreach($send_openids as $openid){
                $template_msg['data']['touser'] = $openid;
                $result = $this->wechat_obj->sendTemplateMsg($template_msg['data']);
                if(!$result){
                    //如果发生错误会提醒管理员
                    // echo json(['status' => -1 ,'error' => 'send template error']);
                    echo $openid;
                }
            }
            //队列全部执行完并提醒管理员 return只是暂时的 删除队列
            $return = $this->HTQClient->deleteQueue($template_msg['queue_name']);
            if ($return['error_code'] == 1004) {
                //删除失败
                $arr_data = [
                    'type' => 'push_message',
                    'data' => [
                        'uid' => $this->config['uid'],
                        'status' => -1,
                        'title' => '模板消息',
                        'message' => "公众号 ".$this->config['wxname']." 模板消息队列删除失败,需联系管理员",
                    ],
                ];
            } else {
                $arr_data = [
                    'type' => 'push_message',
                    'data' => [
                        'uid' => $this->config['uid'],
                        'status' => 1,
                        'title' => '模板消息',
                        'message' => "公众号 ".$this->config['wxname']." 模板消息以全部发送成功!",
                    ],
                ];
            }

            sendWebSocket($arr_data);
            $this->pushmessage_model->allowField(true)->save($arr_data['data']);
            return json(['status' => 1 ,'msg' => 'ok']);
        }else{
            return json(['status' => -1 ,'error' => 'post method error']);
        }
    }

    

    public function queue(){
        $template_msg = $this->request->post();
        //队列名称
        $queue_name = 'queue_'.date('Ymd').'_'.session::get('admin_id').date('His').rand(1,9999);
        $template_msg['queue_name'] = $queue_name;
        $str = base64_encode(json_encode($template_msg));
        $url = QUEUE_URL.'/api/Template/sendTemplateMsg';
        $ret = $this->HTQClient->addQueue($queue_name,"real_time");
        if($ret['error_code'] == 1002){
            //队列已存在请重新操作
            return false;
        }
        $result = $this->actioning_queue($queue_name,$url);
        if($result['error_code'] == 0){
            //队列任务添加成功
            dump($result);
            return '队列任务添加成功';
        }else if($result['error_code'] == 1001){
            //队列任务添加失败
            return false;
        }
    }

    public function queueAll(){
        $ret = $this->HTQClient->allQueue();
        dump($ret);
    }

    public function getQueueAll(){
        $ret = $this->HTQClient->allQueue();
        return $ret;
    }

    public function del(){
        $queueall = $this->getQueueAll();
        foreach($queueall as $v){
            $ret = $this->HTQClient->deleteQueue($v['queue_name']);
            var_dump($ret);
        }
    }

    public function count(){
        $queueall = $this->getQueueAll();
        foreach($queueall as $v){
            $ret = $this->HTQClient->countQueue($v['queue_name']);
            var_dump($ret);
        }
    }

    public function actioning_queue($queue_name,$url){
        $ret = $this->HTQClient->addTask($queue_name,$url);
        return $ret;
    }
    


    public function test(){
        $data = [];
        $str = '{
            "template_id":"6wc9MhDK36MhgujGxjtJ1W9CP_i5SRgIvaB66l4tY4M",
            "url":"https://www.baidu.com",           
            "data":{
                    "first": {
                        "value":"恭喜，测试通过！",
                        "color":"#173177"
                    },
                    "keyword1":{
                        "value":"这是测试业务",
                        "color":"#173177"
                    },
                    "keyword2": {
                        "value":"2018-07-07 10:30",
                        "color":"#173177"
                    },
                    "remark":{
                        "value":"只是测试业务，不用理会，谢谢",
                        "color":"#173177"
                    }
            }
        }';

        $data['openid'] = ['o5eJs0esozstbeHTlwNUXXyOkpE8',
        'o5eJs0SvHwzL7z3XOL5RHtFZVE4I',
        'o5eJs0ceePyPjhBJ-F9yD-ERAcmY',
        'o5eJs0T49hHqPrcjSCHvgTZdBrYs',
        'o5eJs0bS_ua371awfcd0pkP8mtLc',
        'o5eJs0RZl8tf-yCdpTLUA2KSAaaM'];
        $data['data'] = json_decode($str,true);

        return $data;
    }

    function test2(){
        $template_msg = $this->request->post();
        dump($template_msg);
    }

    public function test3(){
        $data = $this->request->post();
        $template_msg = $data['data'];
        $send_openids = $template_msg['openid'];
        foreach($send_openids as $openid){
            file_put_contents('./abc.log',$openid,FILE_APPEND);
            $template_msg['data']['touser'] = $openid;
            $result = $this->wechat_obj->sendTemplateMsg($template_msg['data']);
            if(!$result){
                //如果发生错误会提醒管理员 return只是暂时的
                return json(['status' => -1 ,'error' => 'send template error']);
            }
        }
        //队列全部执行完并提醒管理员 return只是暂时的 删除队列
        $return = $this->HTQClient->deleteQueue($template_msg['queue_name']);
        if($return['error_code'] == 1004){
            //删除失败
            return false;
        }
        return json(['status' => 1 ,'mag' => 'ok']);
    }
}